<template>
  <div class="system-sensors-container">
    <el-card shadow="hover">
        <div class="system-sensors-search mb15">
            <el-form :model="tableData.param" ref="queryRef" :inline="true" label-width="100px">
            <el-row>                
                <el-col :span="8" class="colBlock">
                  <el-form-item label="序号" prop="id">
                    <el-input
                        v-model="tableData.param.id"
                        placeholder="请输入序号"
                        clearable                        
                        @keyup.enter.native="sensorsList"
                    />                    
                  </el-form-item>
                </el-col>                
                <el-col :span="8" class="colBlock">
                  <el-form-item label="名称" prop="name">
                    <el-input
                        v-model="tableData.param.name"
                        placeholder="请输入名称"
                        clearable                        
                        @keyup.enter.native="sensorsList"
                    />                    
                  </el-form-item>
                </el-col>                
                <el-col :span="8" :class="!showAll ? 'colBlock' : 'colNone'">
                  <el-form-item>
                    <el-button type="primary"  @click="sensorsList"><el-icon><ele-Search /></el-icon>搜索</el-button>
                    <el-button  @click="resetQuery(queryRef)"><el-icon><ele-Refresh /></el-icon>重置</el-button>
                    <el-button type="primary" link  @click="toggleSearch">
                      {{ word }}
                      <el-icon v-show="showAll"><ele-ArrowUp/></el-icon>
                      <el-icon v-show="!showAll"><ele-ArrowDown /></el-icon>
                    </el-button>
                  </el-form-item>
                </el-col>                
                <el-col :span="8" :class="showAll ? 'colBlock' : 'colNone'">
                  <el-form-item label="imei" prop="imei">
                    <el-input
                        v-model="tableData.param.imei"
                        placeholder="请输入imei"
                        clearable                        
                        @keyup.enter.native="sensorsList"
                    />                    
                  </el-form-item>
                </el-col>                
                <el-col :span="8" :class="showAll ? 'colBlock' : 'colNone'">
                  <el-form-item label="在线状态" prop="status">
                    <el-select v-model="tableData.param.status" placeholder="请选择在线状态" clearable >
                        <el-option
                            v-for="dict in online_status"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                        />
                    </el-select>
                  </el-form-item>
                </el-col>                
                <el-col :span="8" :class="showAll ? 'colBlock' : 'colNone'">
                  <el-form-item label="设备温度" prop="temp">
                    <el-input
                        v-model="tableData.param.temp"
                        placeholder="请输入设备温度"
                        clearable                        
                        @keyup.enter.native="sensorsList"
                    />                    
                  </el-form-item>
                </el-col>                
                <el-col :span="8" :class="showAll ? 'colBlock' : 'colNone'">
                  <el-form-item label="上线时间" prop="connectTime">
                    <el-date-picker
                        clearable  style="width: 200px"
                        v-model="tableData.param.connectTime"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"                    
                        type="datetime"
                        placeholder="选择上线时间"                    
                    ></el-date-picker>
                  </el-form-item>
                </el-col>                
                <el-col :span="8" :class="showAll ? 'colBlock' : 'colNone'">
                  <el-form-item label="离线时间" prop="disconnectTime">
                    <el-date-picker
                        clearable  style="width: 200px"
                        v-model="tableData.param.disconnectTime"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"                    
                        type="datetime"
                        placeholder="选择离线时间"                    
                    ></el-date-picker>
                  </el-form-item>
                </el-col>                
                <el-col :span="8" :class="showAll ? 'colBlock' : 'colNone'">
                  <el-form-item label="x轴倾斜角度" prop="qx">
                    <el-input
                        v-model="tableData.param.qx"
                        placeholder="请输入x轴倾斜角度"
                        clearable                        
                        @keyup.enter.native="sensorsList"
                    />                    
                  </el-form-item>
                </el-col>                
                <el-col :span="8" :class="showAll ? 'colBlock' : 'colNone'">
                  <el-form-item label="y轴倾斜角度" prop="qy">
                    <el-input
                        v-model="tableData.param.qy"
                        placeholder="请输入y轴倾斜角度"
                        clearable                        
                        @keyup.enter.native="sensorsList"
                    />                    
                  </el-form-item>
                </el-col>                
                <el-col :span="8" :class="showAll ? 'colBlock' : 'colNone'">
                  <el-form-item label="振动频率" prop="pl">
                    <el-input
                        v-model="tableData.param.pl"
                        placeholder="请输入振动频率"
                        clearable                        
                        @keyup.enter.native="sensorsList"
                    />                    
                  </el-form-item>
                </el-col>                
                <el-col :span="8" :class="showAll ? 'colBlock' : 'colNone'">
                  <el-form-item label="振幅" prop="weiyi">
                    <el-input
                        v-model="tableData.param.weiyi"
                        placeholder="请输入振幅"
                        clearable                        
                        @keyup.enter.native="sensorsList"
                    />                    
                  </el-form-item>
                </el-col>                
                <el-col :span="8" :class="showAll ? 'colBlock' : 'colNone'">
                  <el-form-item label="速度" prop="sudu">
                    <el-input
                        v-model="tableData.param.sudu"
                        placeholder="请输入速度"
                        clearable                        
                        @keyup.enter.native="sensorsList"
                    />                    
                  </el-form-item>
                </el-col>                
                <el-col :span="8" :class="showAll ? 'colBlock' : 'colNone'">
                  <el-form-item label="报警次数" prop="alarmCnt">
                    <el-input
                        v-model="tableData.param.alarmCnt"
                        placeholder="请输入报警次数"
                        clearable                        
                        @keyup.enter.native="sensorsList"
                    />                    
                  </el-form-item>
                </el-col>                
                <el-col :span="8" :class="showAll ? 'colBlock' : 'colNone'">
                  <el-form-item label="创建时间" prop="createdAt">
                    <el-date-picker
                        clearable  style="width: 200px"
                        v-model="tableData.param.createdAt"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"                    
                        type="datetime"
                        placeholder="选择创建时间"                    
                    ></el-date-picker>
                  </el-form-item>
                </el-col>            
                <el-col :span="8" :class="showAll ? 'colBlock' : 'colNone'">
                  <el-form-item>
                    <el-button type="primary"  @click="sensorsList"><el-icon><ele-Search /></el-icon>搜索</el-button>
                    <el-button  @click="resetQuery(queryRef)"><el-icon><ele-Refresh /></el-icon>重置</el-button>
                    <el-button type="primary" link  @click="toggleSearch">
                        {{ word }}
                        <el-icon v-show="showAll"><ele-ArrowUp/></el-icon>
                        <el-icon v-show="!showAll"><ele-ArrowDown /></el-icon>
                    </el-button>
                  </el-form-item>
                </el-col>            
              </el-row>
            </el-form>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  @click="handleAdd"
                  v-auth="'api/v1/system/sensors/add'"
                ><el-icon><ele-Plus /></el-icon>新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="success"
                  :disabled="single"
                  @click="handleUpdate(null)"
                  v-auth="'api/v1/system/sensors/edit'"
                ><el-icon><ele-Edit /></el-icon>修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="danger"
                  :disabled="multiple"
                  @click="handleDelete(null)"
                  v-auth="'api/v1/system/sensors/delete'"
                ><el-icon><ele-Delete /></el-icon>删除</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                type="primary"
                v-if="isAdmin==1"
                :disabled="multiple"
                @click="handleRole(null)"
              ><el-icon><ele-EditPen /></el-icon>修改角色</el-button>
              </el-col>
            </el-row>
        </div>
        <el-table v-loading="loading" :data="tableData.data" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />          
          <el-table-column label="序号" align="center" prop="id"
            min-width="100px"            
             />          
          <el-table-column label="名称" align="center" prop="name"
            min-width="100px"            
             />          
          <el-table-column label="imei" align="center" prop="imei"
            min-width="100px"            
             />          
          <el-table-column label="在线状态" align="center" prop="status"
            min-width="100px"            
          >
            <template #default="scope">

              <span @click="statusPreview(scope.row)" title="点击查看上下线日志"  v-if="scope.row.status" style="color: #08c508;cursor: pointer" >{{ statusFormat(scope.row) }}</span>
              <span @click="statusPreview(scope.row)" title="点击查看上下线日志"  v-else style="color: red;cursor: pointer" >{{ statusFormat(scope.row) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="设备温度" align="center" prop="temp"
            min-width="100px"            
             />          
          <el-table-column label="上线时间" align="center" prop="connectTime"
            min-width="100px"            
            >
            <template #default="scope">
                <span>{{ proxy.parseTime(scope.row.connectTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>          
          <el-table-column label="离线时间" align="center" prop="disconnectTime"
            min-width="100px"            
            >
            <template #default="scope">
                <span>{{ proxy.parseTime(scope.row.disconnectTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>          
          <el-table-column label="x轴向倾斜角度" align="center" prop="qx"
            min-width="100px"            
             />          
          <el-table-column label="y轴向倾斜角度" align="center" prop="qy"
            min-width="100px"            
             />          
          <el-table-column label="振动频率" align="center" prop="pl"
            min-width="100px"            
             />          
          <el-table-column label="振幅" align="center" prop="weiyi"
            min-width="100px"            
             />          
          <el-table-column label="速度" align="center" prop="sudu"
            min-width="100px"            
             />

          <el-table-column label="报警次数" align="center" prop="alarmCnt"

            min-width="100px"
          >

            <template #default="scope">
              <span style="color: #00a2d4;cursor: pointer;" title="点击查看报警记录" @click="alarmPreview(scope.row)">{{ scope.row.alarmCnt }}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createdAt"
            min-width="100px"            
            >
            <template #default="scope">
                <span>{{ proxy.parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>        
          <el-table-column label="操作" align="center" class-name="small-padding" min-width="200px" fixed="right">
            <template #default="scope">            
              <el-button
                type="primary"
                link
                @click="handleView(scope.row)"
                v-auth="'api/v1/system/sensors/view'"
              ><el-icon><ele-View /></el-icon>详情</el-button>              
              <el-button
                type="primary"
                link
                @click="handleUpdate(scope.row)"
                v-auth="'api/v1/system/sensors/edit'"
              ><el-icon><ele-EditPen /></el-icon>修改</el-button>
              <el-button
                type="primary"
                link 
                @click="handleInfo(scope.row)"
              ><el-icon><ele-View /></el-icon>曲线图</el-button>
              <el-button
                type="primary"
                link 
                v-if="isAdmin==1"
                @click="handleRole(scope.row)"
              ><el-icon><ele-EditPen /></el-icon>修改角色</el-button>
              <el-button
                type="primary"
                link
                @click="handleDelete(scope.row)"
                v-auth="'api/v1/system/sensors/delete'"
              ><el-icon><ele-DeleteFilled /></el-icon>删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
            v-show="tableData.total>0"
            :total="tableData.total"
            v-model:page="tableData.param.pageNum"
            v-model:limit="tableData.param.pageSize"
            @pagination="sensorsList"
        />
    </el-card>
    <apiV1SystemSensorsAdd
        ref="addRef"        
        :statusOptions="online_status"     
       :roleLists="roleLists"
        @sensorsList="sensorsList"
    ></apiV1SystemSensorsAdd>
    <apiV1SystemSensorsEdit
       ref="editRef"       
       :roleLists="roleLists"
       :statusOptions="online_status"       
       @sensorsList="sensorsList"
    ></apiV1SystemSensorsEdit>
    <apiV1SystemSensorsDetail
      ref="detailRef"      
      :statusOptions="online_status"      
      @sensorsList="sensorsList"
    ></apiV1SystemSensorsDetail>
    <editRole
      ref="editRoleRef"      
      :roleLists="roleLists"
      :statusOptions="online_status"      
      @sensorsList="sensorsList"
    ></editRole>
    <DetailInfo
      ref="DetailInfoRef"      
    ></DetailInfo>
    <log
      ref="logRef"      
    ></log>
    <StatusLog
      ref="statusLogRef"      
    ></StatusLog>
  </div>
</template>
<script lang="ts">
import {toRefs, reactive, onMounted, ref, defineComponent, computed,getCurrentInstance,toRaw} from 'vue';
import {ElMessageBox, ElMessage, FormInstance} from 'element-plus';
import {
    listSensors,
    delSensors,
} from "/@/api/system/sensors";
import {
    SensorsTableColumns,
    SensorsInfoData,
} from "/@/views/system/sensors/list/component/model"
import apiV1SystemSensorsAdd from "/@/views/system/sensors/list/component/add.vue"
import apiV1SystemSensorsEdit from "/@/views/system/sensors/list/component/edit.vue"
import apiV1SystemSensorsDetail from "/@/views/system/sensors/list/component/detail.vue"
import editRole from "/@/views/system/sensors/list/component/editRole.vue"
import DetailInfo from "/@/views/system/sensors/list/component/DetailInfo.vue"
import log from "/@/views/system/sensors/list/component/log.vue"
import StatusLog from "/@/views/system/sensors/list/component/StatusLog.vue"
import { getRoleList} from "/@/api/system/role";
import { Session } from '/@/utils/storage';

export default defineComponent({
    name: "index",
    components:{
        apiV1SystemSensorsAdd,
        apiV1SystemSensorsEdit,
        apiV1SystemSensorsDetail,editRole,DetailInfo,log,
        StatusLog
    },
    setup() {
        const {proxy} = <any>getCurrentInstance()
        const loading = ref(false)
        const queryRef = ref()
        const addRef = ref();
        const editRoleRef = ref();
        const DetailInfoRef = ref();
        const editRef = ref();
        const detailRef = ref();
        const logRef = ref();
        const statusLogRef = ref();
        // 是否显示所有搜索选项
        const showAll =  ref(false)
        // 非单个禁用
        const single = ref(true)
        // 非多个禁用
        const multiple =ref(true)
        const word = computed(()=>{
            if(showAll.value === false) {
                //对文字进行处理
                return "展开搜索";
            } else {
                return "收起搜索";
            }
        })
        // 字典选项数据        
        const {            
            online_status,            
        } = proxy.useDict(            
            'online_status',      
        )        
        const state = reactive({
            ids:[],
            roleLists:[],//角色列表
            isAdmin:0,
            tableData: {
                data: [],
                total: 0,
                loading: false,
                param: {
                    pageNum: 1,
                    pageSize: 10,                    
                    id: undefined,                    
                    name: undefined,                    
                    imei: undefined,                    
                    status: undefined,                    
                    temp: undefined,                    
                    connectTime: undefined,                    
                    disconnectTime: undefined,                    
                    qx: undefined,                    
                    qy: undefined,                    
                    pl: undefined,                    
                    weiyi: undefined,                    
                    sudu: undefined,                    
                    alarmCnt: undefined,                    
                    createdAt: undefined,                    
                    dateRange: []
                },
            },
        });
        // 页面加载时
        onMounted(() => {
            initTableData();
            roleList()
            var userinfo = Session.get("userInfo");
            if(userinfo){
              state.isAdmin = userinfo.isAdmin
            }
        });
        // 修改角色
        const handleRole=(row:any)=>{
          let arr=[]
          let id=null
          if(row){
            arr=[row.imei]
          id=row.id
          }else{
            arr=state.ids
          }
          editRoleRef.value.openDialog(arr,id)
        }
        const roleList = ()=>{
      getRoleList({pageNum: 1,
          pageSize: 100,}).then(res=>{
        const list = res.data.list??[]
       state.roleLists=list
      })
    };
       
     
        // 初始化表格数据
        const initTableData = () => {
            sensorsList()
        };
        /** 重置按钮操作 */
        const resetQuery = (formEl: FormInstance | undefined) => {
            if (!formEl) return
            formEl.resetFields()
            sensorsList()
        };
        // 获取列表数据
        const sensorsList = ()=>{
          loading.value = true
          listSensors(state.tableData.param).then((res:any)=>{
            let list = res.data.list??[];            
            state.tableData.data = list;            
            state.tableData.total = res.data.total;
            loading.value = false
          })
        };
        const toggleSearch = () => {
            showAll.value = !showAll.value;
        }        
        // 在线状态字典翻译
        const statusFormat = (row:SensorsTableColumns) => {
            return proxy.selectDictLabel(online_status.value, row.status);
        }        
        // 多选框选中数据
        const handleSelectionChange = (selection:Array<SensorsInfoData>) => {
            state.ids = selection.map(item => item.imei)
            single.value = selection.length!=1
            multiple.value = !selection.length
        }
        const handleAdd =  ()=>{
            addRef.value.openDialog()
        }
        const handleUpdate = (row: SensorsTableColumns) => {
            if(!row){
                row = state.tableData.data.find((item:SensorsTableColumns)=>{
                    return item.id ===state.ids[0]
                }) as SensorsTableColumns
            }
            editRef.value.openDialog(toRaw(row));
        };
        const handleDelete = (row: SensorsTableColumns) => {
            let msg = '你确定要删除所选数据？';
            let id:number[] = [] ;
            if(row){
            msg = `此操作将永久删除数据，是否继续?`
            id = [row.id]
            }else{
            id = state.ids
            }
            if(id.length===0){
                ElMessage.error('请选择要删除的数据。');
                return
            }
            ElMessageBox.confirm(msg, '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    delSensors(id).then(()=>{
                        ElMessage.success('删除成功');
                        sensorsList();
                    })
                })
                .catch(() => {});
        }
        const handleView = (row:SensorsTableColumns)=>{
            detailRef.value.openDialog(toRaw(row));
        }
        const handleInfo = (row:SensorsTableColumns)=>{
          DetailInfoRef.value.openDialog(row);
        }
        const alarmPreview=(row:SensorsTableColumns)=>{
          logRef.value.openDialog(row);
        }
        const statusPreview=(row:SensorsTableColumns)=>{
          statusLogRef.value.openDialog(row);
      }
        return {
            proxy,
            addRef,editRoleRef,
            editRef,
            detailRef,
            showAll,
            loading,handleInfo,
            single,logRef,statusLogRef,
            multiple,DetailInfoRef,
            word,handleRole,
            queryRef,
            resetQuery,
            sensorsList,
            toggleSearch,            
            statusFormat,
            online_status,            
            handleSelectionChange,
            handleAdd,
            handleUpdate,
            handleDelete,            
            handleView,
            alarmPreview,
          statusPreview,
            ...toRefs(state),
        }
    }
})
</script>
<style lang="scss" scoped>
    .colBlock {
        display: block;
    }
    .colNone {
        display: none;
    }
    .alarmCnt{
      color: #00b7ee;
    }
</style>